const md5 = require('md5');
const jwt = require('jsonwebtoken');
const Users = require('../model/Users');

let primaryKey = '$#^%RXFE^%%%$*&(*#';
let secret = '$%^&&#$%d';
let userController = {};

let oldPwd;
userController.login = async (req, res) => {
  let { username, password } = req.body;
  oldPwd = password;
  // 对密码进行加密
  let secretPwd = md5(password + secret);
  let data = await Users.findOne({ where: { username, password: secretPwd } });
  if (data) {
    //拿到用户数据
    let dataInfo = { id: data.dataValues.id, username };
    // 生成token
    let token = jwt.sign(dataInfo, primaryKey, {
      expiresIn: '10h',
    });
    let refreshToken = jwt.sign(dataInfo, primaryKey, {
      expiresIn: '15d',
    });
    res.json({ code: 20000, message: '登录成功', token, refreshToken });
    return;
  }
  res.json({ code: 20001, message: '用户名或密码错误' });
};
userController.getPwd = async (req, res) => {
  let password = oldPwd;
  res.json({ password });
};
userController.changePwd = async (req, res) => {
  let { newPwd } = req.body;
  let { id } = req.userInfo;
  newPwd = md5(newPwd + secret);
  await Users.update({ password: newPwd }, { where: { id } })
    .then(() => {
      res.json({ code: 20000, message: '修改成功,请重新登录' });
    })
    .catch(() => {
      res.json({ code: 20001, message: '修改失败' });
    });
};
userController.getRefreshToken = (req, res) => {
  let { refreshToken } = req.body;
  try {
    let data = jwt.verify(refreshToken, primaryKey);
    let userInfo = { id: data.id, username: data.username };
    let token = jwt.sign(userInfo, primaryKey, { expiresIn: '10h' });
    res.json({ code: 20000, token });
  } catch (error) {
    res.json({ code: 20001 });
  }
};
module.exports = userController;
